/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fserv.ui;

import fserv.control.CtrlToUser;
import fserv.control.UserToCtrl;
import fserv.entities.Reply;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.Semaphore;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author arthur
 */
public class ClientUI implements CtrlToUser {

	private UserToCtrl ctrl;
	private final Semaphore waitReply = new Semaphore(1, true);

	private ClientUI() {
		waitReply.drainPermits();
		System.out.println("This is our UI");
	}
	
	private static ClientUI instance = null;
	
	public static ClientUI getInstance() {
		if(ClientUI.instance == null) 
			ClientUI.instance = new ClientUI();
		return instance;
				
	}

	public void show() {
		readCommand();
	}

	private void readCommand() {
		try {
			String CurLine = ""; // Line read from standard in
			
			InputStreamReader converter = new InputStreamReader(System.in);
			BufferedReader in = new BufferedReader(converter);
			
			while(!(CurLine.equals("quit"))) {
				System.out.println("> ");
				CurLine = in.readLine();
				
				if (!(CurLine.equals("quit"))){
					ctrl.sendCommand(CurLine);
					waitReply.acquire();
				}
			}
      this.ctrl.quit();
		} catch (IOException ex) {
			Logger.getLogger(ClientUI.class.getName()).log(Level.SEVERE, null, ex);
		} catch (InterruptedException ex) {
			Logger.getLogger(ClientUI.class.getName()).log(Level.SEVERE, null, ex);
		}
	}
	
	
	@Override
	public void replyReceived(Reply rep) {
    System.out.println("---- Received ----");
		System.out.println(rep);
    System.out.println("------------------");
		waitReply.release();
	}

	public void setCtrl(UserToCtrl ctrl) {
		this.ctrl = ctrl;
	}

}
